package com.xjc.infra.db;

import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

public class DataBaseUtil {

    private SqlSessionTemplate sqlSessionTemplate;

    public int insertBySql(Map<String, Object> params, String sqlName) {
        return sqlSessionTemplate.insert(sqlName, params);
    }

    public <T> int insertEntity(T t, String sqlName) {
        return sqlSessionTemplate.insert(sqlName, t);
    }

    public <T> void insertEntitys(List<T> t, String sqlName) {
        if (null == t) {
            return;
        }
        for (int i = 0; i < t.size(); i++) {
            insertEntity(t.get(i), sqlName);
        }
    }
    public <T> int insertEntitysByBatch(List<T> t, String sqlName) {
    	if (null == t) {
    		return -1;
    	}
    	return sqlSessionTemplate.insert(sqlName, t);
    }

    public int updateBySql(Map<String, Object> params, String sqlName) {
        return sqlSessionTemplate.update(sqlName, params);
    }

    public <T> int updateEntity(T t, String sqlName) {
        return sqlSessionTemplate.update(sqlName, t);
    }


    public int deleteBySql(Map<String, Object> params, String sqlName) {
        return sqlSessionTemplate.delete(sqlName, params);
    }

    public <T> int deleteEntity(T t, String sqlName) {
        return sqlSessionTemplate.delete(sqlName, t);
    }
    
    public <T> int deleteEntityByBatch(List<T> t, String sqlName) {
    	if (null == t) {
    		return -1;
    	}
    	return sqlSessionTemplate.delete(sqlName, t);
    }

    public <T> T selectOneBySql(Map<String, Object> params, String sqlName) {
        return sqlSessionTemplate.selectOne(sqlName, params);
    }


    public <T, E> E selectOneBySql(T t, String sqlName) {
        return sqlSessionTemplate.<E>selectOne(sqlName, t);
    }

    public <T, E> List<E> selectListBySql(T t, String sqlName) {
        return sqlSessionTemplate.<E>selectList(sqlName, t);
    }

    /**
     * 通过模板分页查询
     * @param t 行记录类型
     * @param pager 分页page，返回时候加count，总页数
     * @param sqlName sql模板命名空间
     * @return PageList 
     */
    public <T, E> PageList<E> queryListByTemplateWithPage(T t, Pager pager, String sqlName) {
        PageList<E> pageList = new PageList<E>();
        PageHelper.startPage(pager.getPageNumber(), pager.getPageSize(), true);
        List<E> retList = sqlSessionTemplate.<E>selectList(sqlName, t);
        Page<E> page = (Page<E>) retList;
        pager.setRecordCount(new Long(page.getTotal()).intValue());
        pageList.setPager(pager);
        pageList.setList(retList);
        return pageList;
    }
    public SqlSessionTemplate getSqlSessionTemplate() {
        return sqlSessionTemplate;
    }

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

}
